#!/bin/sh

. ./server/config/env
if [ -f ./var/conf/env ]
then
	. ./var/conf/env
fi

# Absolute path this script is in, thus /home/user/bin
BASE=$(dirname "$(readlink -f "$0")")/server
DAEMON_BIN="node $BASE/bin/start.js monitor_port:$MONITOR_PORT"

make_dir()
{
	if [ ! -e $BASE/$DIR_LOG ]
	then
		mkdir -m 0777 -p $BASE/$DIR_LOG
	fi
	if [ ! -e $BASE/$DIR_RUN ]
	then
		mkdir -m 0777 -p $BASE/$DIR_RUN
	fi
}

do_tail()
{
	tail -f $* $BASE/$CONSOLE_LOG_FILE
}

do_daemon()
{
	echo "Starting Server $APP_NAME..."
	make_dir
	do_run --quite cmd:daemon 2>&1 >>$BASE/$CONSOLE_LOG_FILE
	RETVAL="$?"
	return "$RETVAL"
}

do_run()
{
	make_dir
	$DAEMON_BIN $*

	RETVAL="$?"
	return "$RETVAL"
}

do_stop()
{
	$DAEMON_BIN cmd:stop

	RETVAL="$?"
	return "$RETVAL"
}

do_kill()
{
	$DAEMON_BIN cmd:kill

	RETVAL="$?"
	return "$RETVAL"
}

do_reload()
{
	$DAEMON_BIN cmd:reload

	RETVAL="$?"
	return "$RETVAL"
}

do_status()
{
	$DAEMON_BIN cmd:status

	RETVAL="$?"
	return "$RETVAL"
}

do_monitor()
{
	$DAEMON_BIN cmd:monitor signal:$1 target_pid:$2

	RETVAL="$?"
	return "$RETVAL"
}

case "$1" in
	run)
		echo "Starting Server $APP_NAME..."
		do_run ${*:2}
		;;
	monitor)
		do_monitor $2 $3
		;;
	start)
		do_daemon
		;;
	stop)
		do_stop
		;;
	kill)
		do_kill
		;;
	restart)
		do_stop
		case "$?" in
			0|1)
				do_daemon
				;;
			*)
				echo "Daemon $APP_NAME Stop Failure"
				;;
		esac
		;;
	reload)
		do_reload
		;;
	status)
		do_status
		;;
	tail)
		do_tail ${*:2}
		;;
	*)
		echo "Usage: $0 {start|run|stop|kill|restart|reload|status}" >&2
		exit 3
		;;
esac
exit $RETVAL
